from django.shortcuts import render,redirect,HttpResponse

# Create your views here.

from django.views import View
import json

class Test(View):
	def get(self,request,*args,**kwargs):
		return HttpResponse('123')

	def post(self,request,*args,**kwargs):
		pass


class Login(View):
	def get(self,request,*args,**kwargs):
		return render(request, 'login.html')

	def post(self,request,*args,**kwargs):
		'''code   1000 表示正常用户
		          1001 表示用户无效
		          1002 表示无该用户
		'''
		# from django.contrib.auth.hashers import make_password, check_password   #用于生成加密密码和验证加密密码，django自带的
		result = {'code':None,'isFlag':False,'Message':None}
		username = request.POST.get('username')
		passwd = request.POST.get('password')
		from django.contrib.auth import authenticate
		user = authenticate(username=username, password=passwd)
		if user is not None:
			# the password verified for the user

			if user.is_active:
				username = user.last_name + user.first_name
				request.session['userid'] = user.id
				request.session['user'] = user.username
				request.session['username'] = username
				result['code'] = 1000
				result['isFlag'] = True
				result['message'] = '欢迎你 %s ，您的登录' % username
				result['userid'] = request.session.get('userid')

				return HttpResponse(json.dumps(result, ensure_ascii=False))
			else:
				result['code'] = 1001
				result['isFlag'] = False
				result['message'] = '账户存在异常，请联系管理员QQ506556658'
				return HttpResponse(json.dumps(result,ensure_ascii=False))
		else:
			result['code'] = 1002
			result['isFlag'] = False
			result['message'] = '账户存在异常，请联系管理员QQ506556658'
			return HttpResponse(json.dumps(result, ensure_ascii=False))


def logout(request):
	request.session.clear()
	return redirect('/login')







